/*
 * Copyright DimYLiK.
 */

package com.example.myapp.client.components;

import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.TextBox;

public class DigitTextBox extends TextBox {
    private int minMaxLimit;
    private final Boolean isMax;

    public DigitTextBox(final int length, int minMaxLimit, final Boolean isMax) {
        this.minMaxLimit = minMaxLimit;
        this.isMax = isMax;

        setStyleName("digitTextBox");
        setValue(String.valueOf(length));
        if (isMax == null) {
            setTitle("From 1 to " + minMaxLimit);
        } else if (Boolean.TRUE.equals(isMax)) {
            setTitle("Max value " + minMaxLimit);
        } else {
            setTitle("Min value " + minMaxLimit);
        }
    }

    public void addCustomChangeHandler(final DigitTextBox anotherTextBox) {
        addKeyUpHandler(new KeyUpHandler() {
            public void onKeyUp(KeyUpEvent event) {
                String value = getValue();
                if (value != null && isDigit(value)) {
                    int intValue = Integer.valueOf(value);
                    if (anotherTextBox == null) {
                        if (intValue < 1 || intValue > minMaxLimit) {
                            value = String.valueOf(minMaxLimit);
                        }
                    } else {
                        int anotherValue = Integer.valueOf(anotherTextBox.getValue());
                        if (Boolean.TRUE.equals(isMax) &&
                                (intValue < anotherValue || intValue > minMaxLimit)) {
                            value = String.valueOf(minMaxLimit);
                        } else if (Boolean.FALSE.equals(isMax) &&
                                (intValue > anotherValue || intValue < minMaxLimit)) {
                            value = String.valueOf(minMaxLimit);
                        }
                    }
                } else {
                    value = String.valueOf(minMaxLimit);
                }
                setValue(value);
            }
        });
    }

    private static boolean isDigit(String value) {
        if (value != null) {
            try {
                Integer.valueOf(value);
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }
        return false;
    }
}
